from rest_framework import serializers
from .models import Document
import os

class DocumentSerializer(serializers.ModelSerializer):
    file_url = serializers.SerializerMethodField()
    file_size_formatted = serializers.SerializerMethodField()
    title = serializers.CharField(required=False)  # 标题字段可选
    
    class Meta:
        model = Document
        fields = ['id', 'title', 'file', 'file_url', 'file_type', 
                 'file_size', 'file_size_formatted', 'upload_time', 
                 'upload_ip', 'download_count']
        read_only_fields = ['file_url', 'file_size_formatted', 
                          'upload_time', 'upload_ip', 'download_count',
                          'file_type', 'file_size']  # 这些字段将自动填充
    
    def get_file_url(self, obj):
        request = self.context.get('request')
        if obj.file and hasattr(obj.file, 'url'):
            return request.build_absolute_uri(obj.file.url) if request else obj.file.url
        return None
    
    def get_file_size_formatted(self, obj):
        """返回格式化的文件大小"""
        size = obj.file_size
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size < 1024.0:
                return f"{size:.1f} {unit}"
            size /= 1024.0
        return f"{size:.1f} PB"

    def create(self, validated_data):
        # 如果没有提供标题，使用文件名作为标题
        if not validated_data.get('title'):
            file_name = validated_data['file'].name
            validated_data['title'] = os.path.splitext(file_name)[0]
        
        # 自动填充文件类型
        file_name = validated_data['file'].name
        validated_data['file_type'] = os.path.splitext(file_name)[1][1:].upper()
        
        # 自动填充文件大小
        validated_data['file_size'] = validated_data['file'].size
        
        return super().create(validated_data) 